<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\web\controller;

use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsOrder as OrderModel;

class Pay extends Base
{

    /**
     * 支付预览页
     */
    public function preview()
    {
        $id = $this->request->route->param('id');

        if (!$id) {
            return $this->render('404', ['title' => '订单不存在']);
        }

        // 如果ID是商品ID，则显示商品支付页面
        if (is_numeric($id)) {
            $goods = GoodsModel::where([
                'status' => 1,
                'id'     => $id
            ])->find();

            if (!$goods) {
                return $this->render('404', ['title' => trans('goods_not_exists')]);
            }

            // 处理价格显示
            $goods->is_free = ($goods->price <= 0);

            return $this->render('pay/preview', [
                'title' => '支付 - ' . $goods->name,
                'goods' => $goods,
                'type'  => 'goods',
            ]);
        } else {
            // 如果是订单号，则显示订单支付页面
            $order = OrderModel::where([
                'trade_no' => $id,
                'status'   => ['in', [0, 1]] // 未支付或支付中
            ])->find();

            if (!$order) {
                return $this->render('404', ['title' => '订单不存在或已支付']);
            }

            // 获取订单商品信息
            $goods = GoodsModel::where('id', $order->goods_id)->find();

            // 处理价格显示
            if ($goods) {
                $goods->is_free = ($goods->price <= 0);
            }

            return $this->render('pay/preview', [
                'title' => '支付订单 - ' . $order->trade_no,
                'order' => $order,
                'goods' => $goods,
                'type'  => 'order',
            ]);
        }
    }

    /**
     * 创建订单（AJAX接口）
     */
    public function createOrder()
    {
        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $goods_id = $this->request->post('goods_id');
        $quantity = $this->request->post('quantity', 1);

        if (!$goods_id) {
            return $this->error('商品ID不能为空');
        }

        // 获取商品信息
        $goods = GoodsModel::where([
            'status' => 1,
            'id'     => $goods_id
        ])->find();

        if (!$goods) {
            return $this->error(trans('goods_not_exists'));
        }

        try {
            // 创建订单
            $order               = new OrderModel();
            $order->trade_no     = $this->generateTradeNo();
            $order->goods_id     = $goods_id;
            $order->goods_name   = $goods->name;
            $order->goods_price  = $goods->price;
            $order->quantity     = $quantity;
            $order->total_amount = bcmul($goods->price, $quantity, 2);
            $order->user_id      = $this->user_id ?: 0; // 支持免登录购买
            $order->status       = 0; // 未支付
            $order->create_time  = time();
            $order->save();

            return $this->success('订单创建成功', [
                'order_id'     => $order->id,
                'trade_no'     => $order->trade_no,
                'total_amount' => $order->total_amount,
            ]);

        } catch (\Exception $e) {
            return $this->error('订单创建失败: ' . $e->getMessage());
        }
    }

    /**
     * 支付页面
     */
    public function pay()
    {
        $trade_no = $this->request->get('trade_no');
        $pay_type = $this->request->get('pay_type', 'alipay');

        if (!$trade_no) {
            return $this->error('订单号不能为空');
        }

        $order = OrderModel::where([
            'trade_no' => $trade_no,
            'status'   => ['in', [0, 1]]
        ])->find();

        if (!$order) {
            return $this->error('订单不存在或已支付');
        }

        // 这里应该调用具体的支付接口
        // 暂时返回支付页面
        return $this->render('pay/pay', [
            'title'    => '支付',
            'order'    => $order,
            'pay_type' => $pay_type,
        ]);
    }

    /**
     * 支付结果页面
     */
    public function result()
    {
        $trade_no = $this->request->get('trade_no');
        $status   = $this->request->get('status', 'success'); // success, failed, pending

        if (!$trade_no) {
            return $this->render('404', ['title' => '订单不存在']);
        }

        $order = OrderModel::where('trade_no', $trade_no)->find();

        if (!$order) {
            return $this->render('404', ['title' => '订单不存在']);
        }

        $title = '支付结果';
        switch ($status) {
            case 'success':
                $title = '支付成功';
                break;
            case 'failed':
                $title = '支付失败';
                break;
            case 'pending':
                $title = '支付处理中';
                break;
        }

        return $this->render('pay/result', [
            'title'  => $title,
            'order'  => $order,
            'status' => $status,
        ]);
    }

    /**
     * 生成订单号
     */
    private function generateTradeNo()
    {
        return date('YmdHis') . rand(1000, 9999);
    }

    /**
     * 获取支付网关（直接使用API项目）
     */
    public function getPayChannel()
    {
        $apiPay = new \app\api\controller\Pay();
        return $apiPay->getPayChannel();
    }

    /**
     * 订单预检测
     * @param array $post 表单数据
     */
    private function checkBuyerStatus()
    {
        if ($this->user_id) {
            $user = (new \app\common\model\User())->where('status', 1)->find($this->user_id);
            if (empty($user)) {
                throw new \Exception("买家不存在");
            }
            if ($user->is_freeze == 1) {
                throw new \Exception("买家已被禁止下单");
            }
        }
    }

    /**
     * 创建支付订单
     */
    public function payOrder()
    {

        $this->checkBuyerStatus();

        $orderService = new \app\service\api\OrderService();
        $data         = $orderService->createOrder([
            'goods_id' => inputs('goods_id/s', ''),
            'pid'      => inputs('pid/s', ''),
        ]);

        // 如果价格为0 则立即完成订单 todo
        if (empty($data['price'])) {
            throw new \Exception("免费商品，无需支付");
        }

        // 创建支付关联 如果存在用户
        if ($this->user_id) {
            $data['user_id']  = $this->user_id;
            $data['order_id'] = $data['id'];
            (new \app\common\model\UserOrder())->create($data);
        }
        return $this->success("订单创建成功！请及时支付！", $data);
    }

    /**
     * 检查订单状态（直接使用API项目）
     */
    public function orderStatus()
    {
        $apiPay = new \app\api\controller\Pay();
        return $apiPay->orderStatus();
    }

    /**
     * 关闭订单（直接使用API项目）
     */
    public function orderClose()
    {
        $apiPay = new \app\api\controller\Pay();
        return $apiPay->orderClose();
    }
}
